package com.xmy.pc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class B {
    public static void main(String[] args) {
        Data2 data = new Data2();
        new Thread(()->{
            for (int i = 0; i <10 ; i++) {
                data.printA();
            }
        },"A").start();
        new Thread(()->{
            for (int i = 0; i <10 ; i++) {
                data.printB();
            }
        },"B").start();
        new Thread(()->{
            for (int i = 0; i <10 ; i++) {
                data.printC();
            }
        },"C").start();
    }
}

// 判断等到，业务，通知
class Data2{ //数字 资源类
    private int number=0;

    Lock lock = new ReentrantLock();
    Condition A = lock.newCondition();
    Condition B = lock.newCondition();
    Condition C = lock.newCondition();

    public void printA(){
        lock.lock();
        try {
            while (number%3!=0){//判断
                A.await();
            }
            number++;
            System.out.println(Thread.currentThread().getName()+"正在执行！");
            B.signal();//唤醒B线程
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printB(){
        lock.lock();
        try {
            while (number%3!=1){//判断
                B.await();
            }
            number++;
            System.out.println(Thread.currentThread().getName()+"正在执行！");
            C.signal();//唤醒C线程
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printC(){
        lock.lock();
        try {
            while (number%3!=2){//判断
                C.await();
            }
            number++;
            System.out.println(Thread.currentThread().getName()+"正在执行！");
            A.signal();//唤醒A线程
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

}

